<template>
  <div class="selection-result">
      <a-tabs defaultActiveKey="1">
        <a-tab-pane tab="已选课程" key="1">
          <a-table
            :columns="selectedColumns"
            :dataSource="selectedCourses"
            rowKey="id"
            :pagination="false"
          >
            <span slot="timeLocation" slot-scope="text, record">
              <div>{{ record.time }}</div>
              <div>{{ record.location }}</div>
            </span>

            <span slot="status" slot-scope="text, record">
              <a-tag :color="getStatusColor(record.status)">
                {{ record.status }}
              </a-tag>
            </span>
            
            <span slot="action" slot-scope="text, record">
              <a-button type="link" size="small" @click="handleDropCourse(record)">退选</a-button>
            </span>
          </a-table>
        </a-tab-pane>
        
        <a-tab-pane tab="选课统计" key="2">
          <div class="statistics">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-card title="已选课程" :bordered="false">
                  <h2>{{ selectedCourses.length }} 门</h2>
                </a-card>
              </a-col>
              <a-col :span="12">
                <a-card title="已获学分" :bordered="false">
                  <h2>{{ totalCredits }} 学分</h2>
                </a-card>
              </a-col>
              <!-- <a-col :span="8">
                <a-card title="剩余选课币" :bordered="false">
                  <h2>{{ remainingCoins }} 个</h2>
                </a-card>
              </a-col> -->
            </a-row>
            
            <a-divider />
            
            <h3>课程时间分布</h3>
            <div class="time-distribution">
              <a-table
                :columns="timeColumns"
                :dataSource="timeDistribution"
                rowKey="time"
                :pagination="false"
                size="small"
              />
            </div>
            
            <a-divider />
            
            <h3>学分分布</h3>
            <div class="credit-distribution">
              <a-radio-group v-model="creditType" buttonStyle="solid" style="margin-bottom: 16px;">
                <a-radio-button value="category">按课程类别</a-radio-button>
                <a-radio-button value="department">按开课院系</a-radio-button>
              </a-radio-group>
              <a-table
                :columns="creditColumns"
                :dataSource="creditDistribution"
                rowKey="type"
                :pagination="false"
                size="small"
              />
            </div>
          </div>
        </a-tab-pane>
        
        <a-tab-pane tab="冲突检测" key="3" v-if="hasConflicts">
          <a-alert
            message="选课冲突警告"
            description="您选择的课程存在时间冲突，请及时调整！"
            type="warning"
            showIcon
            style="margin-bottom: 20px;"
          />
          <a-table
            :columns="conflictColumns"
            :dataSource="conflictCourses"
            rowKey="id"
            :pagination="false"
          >
            <span slot="time" slot-scope="text, record">
              {{ record.time }}
            </span>
            <span slot="action" slot-scope="text, record">
              <a-button type="link" size="small" @click="handleDropCourse(record)">退选</a-button>
            </span>
          </a-table>
        </a-tab-pane>
      </a-tabs>
  </div>
</template>

<script>
const selectedColumns = [
  {
    title: '课程编号',
    dataIndex: 'id',
    key: 'id',
    width: 100
  },
  {
    title: '课程名称',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '学分',
    dataIndex: 'credit',
    key: 'credit',
    width: 80
  },
  {
    title: '任课教师',
    dataIndex: 'teacher',
    key: 'teacher',
    width: 120
  },
  {
    title: '时间/地点',
    key: 'timeLocation',
    scopedSlots: { customRender: 'timeLocation' },
    width: 180
  },
  {
    title: '选课状态',
    key: 'status',
    scopedSlots: { customRender: 'status' },
    width: 100
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    width: 80
  }
];

const timeColumns = [
  {
    title: '时间',
    dataIndex: 'time',
    key: 'time',
    width: 120
  },
  {
    title: '周一',
    dataIndex: 'mon',
    key: 'mon',
    width: 150
  },
  {
    title: '周二',
    dataIndex: 'tue',
    key: 'tue',
    width: 150
  },
  {
    title: '周三',
    dataIndex: 'wed',
    key: 'wed',
    width: 150
  },
  {
    title: '周四',
    dataIndex: 'thu',
    key: 'thu',
    width: 150
  },
  {
    title: '周五',
    dataIndex: 'fri',
    key: 'fri',
    width: 150
  }
];

const conflictColumns = [
  {
    title: '冲突课程',
    dataIndex: 'name',
    key: 'name',
    width: 150
  },
  {
    title: '冲突时间',
    key: 'time',
    scopedSlots: { customRender: 'time' },
    width: 150
  },
  {
    title: '任课教师',
    dataIndex: 'teacher',
    key: 'teacher',
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    width: 80
  }
];

const creditColumns = [
  {
    title: '类别',
    dataIndex: 'type',
    key: 'type',
    width: 150
  },
  {
    title: '课程数',
    dataIndex: 'count',
    key: 'count',
    width: 100
  },
  {
    title: '总学分',
    dataIndex: 'credits',
    key: 'credits',
    width: 100
  },
  {
    title: '占比',
    dataIndex: 'percentage',
    key: 'percentage',
    width: 100
  }
];

export default {
  props: {
    result: {
      type: Object,
      default: () => ({})
    },
    courses: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      selectedColumns,
      timeColumns,
      conflictColumns,
      creditColumns,
      selectedCourses: [],
      timeDistribution: [],
      conflictCourses: [],
      remainingCoins: 100,
      creditType: 'category',
      creditDistribution: []
    };
  },
  computed: {
    totalCredits() {
      return this.selectedCourses.reduce((sum, course) => sum + course.credit, 0);
    },
    hasConflicts() {
      return this.conflictCourses.length > 0;
    }
  },
  watch: {
    creditType() {
      this.generateCreditDistribution();
    }
  },
  created() {
    this.fetchSelectionResult();
  },
  methods: {
    fetchSelectionResult() {
      // 模拟获取选课结果
      this.selectedCourses = this.generateMockSelectedCourses();
      this.timeDistribution = this.generateTimeDistribution();
      this.conflictCourses = this.detectConflicts();
      this.generateCreditDistribution();
    },
    
    generateMockSelectedCourses() {
      const realCourses = [
        {
          id: 'CS101',
          name: '计算机科学导论',
          category: '专业必修',
          department: '信息工程系',
          credit: 3,
          teacher: '王雪',
          time: '周一 1-2节',
          location: '1号教学楼101',
          status: '已确认'
        },
        {
          id: 'ENG102',
          name: 'PLC与工业控制技术(二)',
          category: '公共必修',
          department: '外语学院',
          credit: 2,
          teacher: '李红梅',
          time: '周三 5-6节',
          location: '教学楼C301',
          status: '已确认'
        },
        {
          id: 'CS202',
          name: '数据结构与算法',
          category: '专业必修',
          department: '信息工程系',
          credit: 4,
          teacher: '阿依古丽·买买提',
          time: '周五 1-2节',
          location: '教学楼D401',
          status: '待抽签'
        },
      ];
      
      return realCourses;
    },
    
    generateTimeDistribution() {
      const timeSlots = [];
      for (let i = 1; i <= 5; i++) {
        timeSlots.push({
          time: `${i}-${i+1}节`,
          mon: this.getCourseAtTime('一', i),
          tue: this.getCourseAtTime('二', i),
          wed: this.getCourseAtTime('三', i),
          thu: this.getCourseAtTime('四', i),
          fri: this.getCourseAtTime('五', i)
        });
      }
      return timeSlots;
    },
    
    getCourseAtTime(weekday, section) {
      const course = this.selectedCourses.find(c => {
        return c.time.includes(`周${weekday}`) && 
               c.time.includes(`${section}-${section+1}节`);
      });
      return course ? `${course.name}@${course.location}` : '';
    },
    
    detectConflicts() {
      const conflicts = [];
      const timeMap = {};
      
      this.selectedCourses.forEach(course => {
        const timeKey = course.time;
        if (timeMap[timeKey]) {
          if (!conflicts.some(c => c.id === timeMap[timeKey].id)) {
            conflicts.push(timeMap[timeKey]);
          }
          conflicts.push(course);
        } else {
          timeMap[timeKey] = course;
        }
      });
      
      return conflicts;
    },
    
    generateCreditDistribution() {
      if (this.creditType === 'category') {
        const categories = {};
        this.selectedCourses.forEach(course => {
          if (!categories[course.category]) {
            categories[course.category] = {
              count: 0,
              credits: 0
            };
          }
          categories[course.category].count++;
          categories[course.category].credits += course.credit;
        });
        
        this.creditDistribution = Object.keys(categories).map(key => ({
          type: key,
          count: categories[key].count,
          credits: categories[key].credits,
          percentage: `${Math.round(categories[key].credits / this.totalCredits * 100)}%`
        }));
      } else {
        const departments = {};
        this.selectedCourses.forEach(course => {
          if (!departments[course.department]) {
            departments[course.department] = {
              count: 0,
              credits: 0
            };
          }
          departments[course.department].count++;
          departments[course.department].credits += course.credit;
        });
        
        this.creditDistribution = Object.keys(departments).map(key => ({
          type: key,
          count: departments[key].count,
          credits: departments[key].credits,
          percentage: `${Math.round(departments[key].credits / this.totalCredits * 100)}%`
        }));
      }
    },
    
    getStatusColor(status) {
      const colors = {
        '已确认': 'green',
        '待抽签': 'orange'
      };
      return colors[status] || 'blue';
    },
    
    handleDropCourse(course) {
      this.$confirm({
        title: '确认退选课程?',
        content: `确定要退选课程《${course.name}》吗？`,
        onOk: () => {
          this.selectedCourses = this.selectedCourses.filter(c => c.id !== course.id);
          this.conflictCourses = this.detectConflicts();
          this.timeDistribution = this.generateTimeDistribution();
          this.generateCreditDistribution();
          this.$message.success(`已成功退选课程《${course.name}》`);
        }
      });
    }
  }
};
</script>

<style scoped>
.selection-result {
  margin: 0;
  padding:20px;
  padding-top:0;
}
.statistics {
  padding: 20px;
}
.time-distribution, .credit-distribution {
  margin-top: 20px;
}
</style>